import React, {useEffect, useState} from "react";
import {Button, Form, Input, message, Modal, Select, Space, Table} from 'antd';
import {SearchOutlined, SyncOutlined, WarningOutlined,} from '@ant-design/icons';
import UserModal from "./component/userModal";
import DistributeRole from "./component/distributeRole";
import {useTranslation} from 'react-i18next';
import {apiInterceptors, getUserList, updateUser as updateUserById} from '@/client/api';
import {deleteUserById} from "../../client/api";
import useSetTableScroll from '@/hooks/use-table-scroll'

const { confirm } = Modal

const User = () => {
  const [queryForm] = Form.useForm();
  const { t } = useTranslation();

  const [handleType, setHandleType] = useState('add')
  const [isModalOpen, setIsModalOpen] = useState(false)
  let [tableData, setTableData] = useState([])
  const [userId, setUserId] = useState('')
  const [isShowDistribute, setShowDistribute] = useState(false)
  const [roleList, setRoleList] = useState([])

  let [pagination, setPagination] = useState({
    total: 0,
    current: 1,
    pageSize: 10
  })
  const tableHeight = useSetTableScroll()

  const columns = [
    {
      title: '用户名称',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '租户名称',
      dataIndex: 'tenant_names',
      key: 'tenant_names',
      render: (_:any, record: any) => {
        return record.tenant_names.toString()
      }
    },
    {
      title: '所属角色',
      dataIndex: 'role_list',
      key: 'role_list',
      render:(_:any, record:any) => {
        return record.role_list.map((item: any) => item.name).toString()
      }
    },
    {
      title: '创建人姓名',
      dataIndex: 'display_name',
      key: 'display_name',
    },
    {
      title: '创建人ldap',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (_:any, record:any) => {
        return record.is_active ? '启用' : '禁用'
      }
    },
    {
      title: '操作',
      render: (_:any, record:any) => (
        <Space size="middle">
          <a onClick={() => updateUser(record)}>修改</a>
          {/*<a onClick={() => deleteUser(record)}>删除</a>*/}
          <a onClick={() => distributeUser(record)}>分配角色</a>
          {
            record.is_active === false ?
              <a onClick={() => statusHandle(record, true)}>启用</a>
              :
              <a onClick={() => statusHandle(record, false)}>禁用</a>
          }
        </Space>
      )
    }
  ]

  const paginationChange = (page:number, size:number) => {
    const {total} = pagination
    setPagination({
      total: total,
      current: page,
      pageSize: size
    })
  }
  function searchQueryFn() {
    console.log(queryForm.getFieldsValue())
    setPagination({ ...pagination, current: 1 })
    getTableList()
  }
  function resetQueryFn() {
    queryForm.resetFields()
    setPagination({ ...pagination, current: 1 })
    getTableList()
  }
  function setModal(e: boolean) {
    setIsModalOpen(e)
  }
  const updateUser = (data:any) => {
    setHandleType('edit')
    setUserId(data.id)
    setModal(true)
  }
  const distributeUser = (data: any) => {
    setUserId(data.id)
    setRoleList(data.role_list)
    setShowDistribute(true)
  }
  const deleteUser = (data:any) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定删除该用户吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk() {
        const [err] = await apiInterceptors(deleteUserById(data.id))
        if (!err) {
          message.success('删除成功')
          searchQueryFn()
        }
      },
    });
  }
  const statusHandle = async (record, type) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定${record.is_active ? '禁用' : '启用'}该用户吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk() {
        const [err] = await apiInterceptors(updateUserById({ is_active: type, id: record.id }))
        if (!err) {
          message.success('操作成功')
          searchQueryFn()
        } else {
          return
        }
      },
    });

  }
  const getTableList = async () => {
    const queryData = queryForm.getFieldsValue()
    const param = {
      page_num: pagination.current,
      page_size: pagination.pageSize,
      ...queryData,
    }
    console.log('pagination2', pagination.current)
    const [_, data] = await apiInterceptors(getUserList(param))
    setTableData(data?.data)
    setPagination({
      pageSize: pagination.pageSize,
      total: data?.total,
      current: pagination.current
    })
  }
  const createHandle = () => {
    setHandleType('add')
    setModal(true)
  }
  useEffect(() => {
    // calcTableHeight()
    getTableList()
  }, [pagination.current, pagination.pageSize])
  return (
      <div className="p-5 marvel_table_container">
        <div className="top_search p-5 bg-white dark:bg-[#232734]">
          <Form form={queryForm} layout="inline" name={'query'} autoComplete="off" className='cus_form'
                initialValues={{is_active: true}}
                labelAlign='left'
          >
            {/*<Space wrap={true}>*/}
            {/*<Form.Item label="用户ID" name="user_id">*/}
            {/*  <Input style={{ width: 240 }} placeholder="请输入用户ID" allowClear onPressEnter={searchQueryFn} />*/}
            {/*</Form.Item>*/}
            <Form.Item label="用户名称" name="name" colon={false}>
              <Input style={{ width: 240 }} placeholder="请输入用户名称" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>
            <Form.Item label="租户ID" name="tenant_id">
              <Input style={{ width: 240 }} placeholder="请输入租户ID" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>
            <Form.Item label="租户名称" name="tenant_name">
              <Input style={{ width: 240 }} placeholder="请输入租户名称" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>
            <Form.Item label="创建人ldap" name="created_by">
              <Input style={{ width: 240 }} placeholder="请输入创建人ldap" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>
            <Form.Item label="状态" name="is_active">
              <Select
                style={{ width: 240 }}
                placeholder="请选择状态"
                onChange={searchQueryFn}
                options={[
                  { value: true, label: '启用' },
                  { value: false, label: '禁用' },
                ]}
              />
            </Form.Item>
            <Form.Item label=''>
              <div style={{width: 240}}>
                <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />} style={{marginRight: '20px'}}>
                  搜索
                </Button>
                <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                  重置
                </Button>
              </div>
            </Form.Item>
            {/*</Space>*/}
          </Form>
        </div>
        <Button type="primary" style={{marginTop: '20px'}} onClick={() => createHandle()}>创建用户</Button>
        <div className="user_table" style={{marginTop: '20px'}}>
          <Table
            columns={columns}
            dataSource={tableData}
            scroll={{y: tableHeight}}
            pagination={{
              ...pagination,
              showTotal: (total, range) => `共 ${total} 条`,
              onChange: paginationChange
            }}
          />
        </div>
        {
          isModalOpen &&
          <UserModal handleType={handleType} isModalOpen={isModalOpen} setModal={ setModal } userId={userId} successCall={searchQueryFn}/>
        }
        {
          isShowDistribute &&
          <DistributeRole userId={userId} successCall={searchQueryFn} setModal={ setShowDistribute } roleList={roleList}/>
        }
      </div>
  )
}

export default User
